package net.guerlab.smart.qcloud.im.client;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.guerlab.smart.qcloud.im.AbstractImRequest;
import net.guerlab.smart.qcloud.im.AbstractImResponse;
import net.guerlab.smart.qcloud.im.ImConstants;
import net.guerlab.smart.qcloud.im.ImException;
import okhttp3.*;

import java.util.Objects;

/**
 * Im客户端-OkHttp实现
 *
 * @author guer
 */
public class OkHttpImClient extends AbstractImClient {

    /**
     * OkHttp请求客户端
     */
    private final OkHttpClient client;

    public OkHttpImClient(Long sdkAppId, String key, String identifier, OkHttpClient client,
            ObjectMapper objectMapper) {
        super(objectMapper, sdkAppId, key, identifier);
        this.client = client;
    }

    @Override
    protected <R extends AbstractImResponse> R executeWithHttpRequest(AbstractImRequest<R> request, String uri,
            ObjectMapper objectMapper) {
        Request.Builder builder = new Request.Builder();

        RequestBody body = RequestBody
                .create(MediaType.parse(ImConstants.DEFAULT_MEDIA_TYPE), request.requestBody(objectMapper));

        builder.url(uri);
        builder.post(body);

        return request.parseResponse(getHttpResponseString(builder), objectMapper);
    }

    private String getHttpResponseString(Request.Builder builder) {
        Call call = client.newCall(builder.build());
        try {
            Response response = call.execute();
            return Objects.requireNonNull(response.body()).string();
        } catch (Exception e) {
            throw new ImException(e.getLocalizedMessage(), e);
        }
    }
}
